package routers

import (
	"time"
	"xinmanpan/app/controllers"
	"xinmanpan/app/middlewares"
	_ "xinmanpan/docs" // 替换为实际的模块路径

	ginSwagger "github.com/swaggo/gin-swagger"
	"github.com/swaggo/gin-swagger/swaggerFiles"

	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

func SetupRouter(db *gorm.DB) *gin.Engine {
	userController := controllers.NewUserController(db)
	emailController := controllers.NewEmailController(db)
	// 显式设置 Gin 运行模式为 debug
	gin.SetMode(gin.DebugMode)
	// 显式设置 Gin 运行模式为 release
	// gin.SetMode(gin.ReleaseMode)

	r := gin.Default()
	// 注册 CORS 中间件
	r.Use(cors.New(cors.Config{
		AllowOrigins:     []string{"*"},                                       // 允许访问的前端 URL
		AllowMethods:     []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"}, // 允许的方法
		AllowHeaders:     []string{"Origin", "Content-Type", "Authorization"}, // 允许的请求头
		AllowCredentials: true,                                                // 允许发送凭证（如 cookies）
		MaxAge:           12 * time.Hour,                                      // 预检请求缓存时间
	}))

	// 提供静态资源
	// r.Static("/assets", "./frontend/assets") // 处理静态资源路径

	// // 提供 HTML 文件
	// r.GET("/", func(c *gin.Context) {
	// 	c.File("./frontend/index.html")
	// })
	// // 修改 Gin 代码，在所有未匹配到的路由请求时返回 index.html
	// r.NoRoute(func(c *gin.Context) {
	// 	c.File("./frontend/index.html")
	// })

	// 注册 Swagger UI 路由
	if gin.Mode() == gin.DebugMode {
		r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
	}

	api := r.Group("/api/v1")
	{
		api.POST("/register", userController.Register)
		api.POST("/login", userController.Login)
		api.POST("/refresh", userController.Refresh)
		api.GET("/protected", middlewares.AuthMiddleware(), userController.Protected)
		api.POST("/email/verification/code/send", middlewares.AuthMiddleware(), emailController.SendVerificationCodeByEmail)
		api.POST("/email/verification/code/verify", middlewares.AuthMiddleware(), emailController.VerifyEmailCode)
		api.POST("/smtp/setting/update", middlewares.AuthMiddleware(), emailController.UpdateXinmanSmtpSetting)
		api.GET("/smtp/setting/get", middlewares.AuthMiddleware(), emailController.GetXinmanSmtpSetting)
	}

	return r
}
